<template>
  <div>
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="searchData" :inline="true" label-width="auto">
        <el-form-item label="分类名称" prop="category_name">
          <el-input v-model="searchData.category_name" placeholder="分类名称" clearable />
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-select v-model="searchData.is_show" placeholder="全部" clearable style="width: 100px">
            <el-option label="全部" value="" />
            <el-option label="显示" :value="1" />
            <el-option label="隐藏" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择时间段" prop="startDate">
          <el-date-picker
            v-model="searchData.startDate"
            type="datetime"
            :clearable="false"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item prop="endDate">
          <el-date-picker
            v-model="searchData.endDate"
            type="datetime"
            :clearable="false"
            placeholder="选择结束日期"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="search">搜索</el-button>
          <el-button icon="refresh" @click="reset(queryFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="position: relative">
      <el-card>
        <el-table :data="categoryData" @selection-change="selectionChange" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>

          <el-table-column label="名称">
            <template #default="{ row }">
              {{ row.category_name }}
            </template>
          </el-table-column>

          <el-table-column label="介绍">
            <template #default="{ row }">
              {{ row.intro }}
            </template>
          </el-table-column>

          <el-table-column label="作者">
            <template #default="{ row }">
              {{ row.admin_id ? row.nickname : "匿名" }}
            </template>
          </el-table-column>

          <el-table-column label="展示">
            <template #default="{ row }">
              {{ row.is_show ? "展示" : "隐藏" }}
            </template>
          </el-table-column>

          <el-table-column label="日期">
            <template #default="{ row }">
              {{ formatDate(row.add_date, "YYYY-MM-DD") }}
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="edit(row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="delCategoryData(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="button">
          <div><el-button @click="delSelectedData">删除选中分类</el-button></div>
          <div><el-button @click="addCategory">添加分类</el-button></div>
          <div>
            <el-pagination
              background
              v-model:page-size="pagesize"
              layout="prev, pager, next, total"
              :total="count"
              v-model:current-page="page"
              @current-change="currentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加的表单 -->
    <div class="addForm" v-show="isShow">
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item label="分类名称">
          <el-input v-model="category_name" />
        </el-form-item>

        <el-form-item label="分类简介">
          <el-input v-model="intro" type="textarea" />
        </el-form-item>

        <el-form-item label="是否显示">
          <el-switch v-model="is_show" />
        </el-form-item>

        <el-form-item label="添加日期时间">
          <el-date-picker
            type="datetime"
            :clearable="false"
            v-model="addDate"
            placeholder="选择添加日期"
          />
        </el-form-item>

        <el-form-item label="分类排序">
          <el-input v-model="sort" />
        </el-form-item>

        <el-form-item label="管理员">
          <el-select v-model="admin_id" placeholder="选择创建的管理员">
            <el-option label="请选择" :value="0" />
            <el-option
              v-for="item in adminData"
              :key="item.admin_id"
              :label="item.nickname || item.username"
              :value="item.admin_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addCategoryData">添加</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 编辑的表单 -->
    <div class="editForm" v-show="isShowEdit">
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item label="分类名称">
          <el-input v-model="editedData.category_name" />
        </el-form-item>

        <el-form-item label="分类简介">
          <el-input type="textarea" v-model="editedData.intro" />
        </el-form-item>

        <el-form-item label="是否显示">
          <el-switch v-model="is_shows" />
        </el-form-item>

        <el-form-item label="添加日期时间">
          <el-date-picker
            type="datetime"
            :clearable="false"
            v-model="add_time"
            placeholder="选择添加日期"
          />
        </el-form-item>

        <el-form-item label="分类排序">
          <el-input v-model="editedData.sort" />
        </el-form-item>

        <el-form-item label="管理员">
          <el-select v-model="editedData.admin_id" placeholder="选择创建的管理员">
            <el-option
              v-for="item in adminData"
              :key="item.admin_id"
              :label="item.nickname || item.username"
              :value="item.admin_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="change">修改</el-button>
          <el-button @click="isShowEdit = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import CategoryAPI, {
  type Category,
  type EditCategory,
  type SearchData,
} from "@/api/system/category.api";
import UserAPI, { AdminInfo } from "@/api/system/user.api";
import { formatDate } from "@/utils/index";
import { FormInstance } from "element-plus";
import moment from "moment";

const page = ref(4);
const pagesize = ref(5);
const count = ref(0);
const categoryData = ref<Category[]>([]);
const selectedId = ref<string>();
// 添加表单的显隐
const isShow = ref(false);
// 编辑表单的显隐
const isShowEdit = ref(false);

// 添加分类数据
const category_name = ref("");
const intro = ref("");
const is_show = ref(false);
const addDate = ref(0);
const sort = ref();
const admin_id = ref(0);

// 管理员数据
const adminData = ref<AdminInfo[]>([]);

// 所编辑分类的数据
const editedData = ref<EditCategory>({
  category_name: "",
  intro: "",
  is_show: false,
  add_date: 0,
  sort: 0,
  admin_id: 0,
});

// 所编辑分类的时间
const add_time = ref("");
// 所编辑分类的显隐
const is_shows = ref(false);

// 搜索的数据
const searchData = ref<SearchData>({
  category_name: "",
  is_show: "",
  startDate: "",
  endDate: "",
});
// 搜索的原始数据

onMounted(() => {
  getCategoryData();
});

// 搜索
const search = async () => {
  if (searchData.value.startDate) {
    searchData.value.startDate = moment(searchData.value.startDate).unix() + "";
  }
  if (searchData.value.endDate) {
    searchData.value.endDate = moment(searchData.value.endDate).unix() + "";
  }
  if (searchData.value.startDate > searchData.value.endDate) {
    ElMessage({
      type: "error",
      message: "日期选择错误",
    });
    return;
  }
  getCategoryData();
};

const queryFormRef = ref<FormInstance>();
// 重置
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getCategoryData();
};

// 添加分类
const addCategory = async () => {
  isShow.value = true;
  // 获取管理员数据
  adminData.value = await UserAPI.getAdmin();
};

// 清空数据方法
const clear = () => {
  category_name.value = "";
  intro.value = "";
  is_show.value = false;
  addDate.value = 0;
  sort.value = undefined;
  admin_id.value = 0;
};

// 取消添加
const cancel = () => {
  clear();
  isShow.value = false;
};

// 添加分类数据
const addCategoryData = async () => {
  // 转换日期
  let add_date = moment(addDate.value).unix();
  if (!sort.value) {
    sort.value = 0;
  }

  const errorMessages: string[] = [];

  if (!category_name.value) {
    errorMessages.push("分类名不能为空");
  }

  if (!intro.value) {
    errorMessages.push("简介不能为空");
  }

  if (!addDate.value) {
    errorMessages.push("日期时间不能为空");
  }

  if (!admin_id.value) {
    errorMessages.push("请选择创建管理员");
  }

  if (errorMessages.length > 0) {
    ElMessage({
      type: "error",
      message: errorMessages.join(";"),
      duration: 5000, // 显示时间延长
    });
    return;
  }

  await CategoryAPI.addCategory(
    category_name.value,
    intro.value,
    is_show.value,
    add_date,
    sort.value,
    admin_id.value
  );
  getCategoryData();
  // 清空输入
  clear();
  isShow.value = false;
  ElMessage({
    type: "success",
    message: "添加成功",
  });
};

// 获得选中分类id
const selectionChange = (rows: Category[]) => {
  let result = rows.map((row) => row.category_id);
  selectedId.value = result.join();
};

// 删除选中分类
const delSelectedData = async () => {
  if (!selectedId.value) {
    ElMessage({
      type: "info",
      message: "请选择分类",
    });
    return;
  }
  await CategoryAPI.delSeleted(selectedId.value!);
  getCategoryData();
  ElMessage({
    type: "success",
    message: "删除选中成功",
  });
};

// 获取分类数据
const getCategoryData = async () => {
  console.log(page.value, pagesize.value, searchData.value);
  let data = await CategoryAPI.getCategory(page.value, pagesize.value, searchData.value);
  categoryData.value = data.result;
  count.value = data.count;
};

// 分页
const currentChange = () => {
  getCategoryData();
};

// 删除分类
const delCategoryData = (row: Category) => {
  ElMessageBox.confirm(`确认删除 ${row.category_name} 吗`, "删除", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await CategoryAPI.delCategory(row.category_id);
      getCategoryData();
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};

// 编辑
const edit = async (row: Category) => {
  isShowEdit.value = true;
  // 获取需要编辑的数据
  let category_id = row.category_id;
  editedData.value = await CategoryAPI.getEditedCategory(category_id);
  is_shows.value = editedData.value.is_show ? true : false;
  add_time.value = formatDate(editedData.value.add_date);
  adminData.value = await UserAPI.getAdmin();
};

// 修改
const change = async () => {
  editedData.value.add_date = moment(add_time.value).unix();
  editedData.value.is_show = is_shows.value;
  const errorMessages: string[] = [];

  if (!editedData.value.category_name) {
    errorMessages.push("分类名不能为空");
  }

  if (!editedData.value.intro) {
    errorMessages.push("简介不能为空");
  }

  if (!editedData.value.add_date) {
    errorMessages.push("日期时间不能为空");
  }

  if (!editedData.value.admin_id) {
    errorMessages.push("请选择创建管理员");
  }

  if (errorMessages.length > 0) {
    ElMessage({
      type: "error",
      message: errorMessages.join(";"),
      duration: 5000, // 显示时间延长
    });
    return;
  }
  await CategoryAPI.changeCategory(editedData.value);
  getCategoryData();
  ElMessage({
    type: "success",
    message: "修改成功",
  });
  isShowEdit.value = false;
};
</script>

<style scoped>
.button {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 20px;
}

.addForm {
  position: fixed;
  top: 0;
  left: 0;
  /* 半透明遮罩 */
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  /* 确保在最上层 */
}

.addForm .el-form {
  width: 600px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.editForm {
  position: fixed;
  top: 0;
  left: 0;
  /* 半透明遮罩 */
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  /* 确保在最上层 */
}

.editForm .el-form {
  width: 600px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
